/**
 * 
 */
package com.example.demo.command;

import java.util.ArrayList;
import java.util.List;

import org.jim.common.ImStatus;
import org.jim.common.packets.Command;
import org.jim.common.packets.Group;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.packets.LoginRespBody;
import org.jim.common.packets.User;
import org.jim.server.command.handler.processor.login.LoginCmdProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.JwtUtil;

/**
 * @author WChao
 *
 */
public class MyLoginServiceProcessor implements LoginCmdProcessor {

	private Logger logger = LoggerFactory.getLogger(MyLoginServiceProcessor.class);

	/**
	 * doLogin方法注意：J-IM登陆命令是根据user是否为空判断是否登陆成功,
	 * 
	 * 当登陆失败时设置user属性需要为空，相反登陆成功user属性是必须非空的;
	 */
	@Override
	public LoginRespBody doLogin(LoginReqBody loginReqBody , ChannelContext channelContext) {
		LoginRespBody loginRespBody = null;
		String token = loginReqBody.getToken();
		if (!JwtUtil.checkJWT(token)) {
			loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP,ImStatus.C10008);
		}else{
			User user;
			try {
				user = new User(JwtUtil.getUserId(token), JwtUtil.getSub(token));
				user.setFriends(initFriends(user));
				user.setGroups(initGroups(user));
				JSONObject extras = new JSONObject();
				extras.put("longitude", loginReqBody.getLongitude());
				extras.put("latitude", loginReqBody.getLatitude());
				user.setExtras(extras);
				loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP, ImStatus.C10007, user);
			} catch (Exception e) {
				logger.error("获取用户名与id失败:", e);
			}
		}
		return loginRespBody;
	}

	public List<Group> initGroups(User user) {
		// 模拟的群组;正式根据业务去查数据库或者缓存;
		List<Group> groups = new ArrayList<Group>();
		return groups;
	}

	public List<Group> initFriends(User user) {
		List<Group> friends = new ArrayList<Group>();
		return friends;
	}
	@Override
	public void onSuccess(ChannelContext channelContext) {
		logger.info("登录成功回调方法");
	}

	@Override
	public boolean isProtocol(ChannelContext channelContext) {
		 
		return true;
	}

	@Override
	public String name() {
		
		return "myLoginServiceProcessor";
	}
}
